<template>
  <div class="padding_20">
    <el-input v-model="searchCondition"
              placeholder="请输入厂家名称"
              class="w-200"
              clearable
              @clear="query" />
    <el-button type="primary"
               @click="query">查 询</el-button>
    <el-button type="primary"
               @click="edit(null)">新 增</el-button>
    <el-table :data="dataList"
              border
              :span-method="handleSpan"
              style="width: 100%; margin-top:30px">
      <el-table-column align="center"
                       label="图标"
                       width="100px"
                       heitht="50px">
        <template slot-scope="scope">
          <el-image :src="scope.row.imageUrl"
                    :preview-src-list="[scope.row.imageUrl]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       prop="name"
                       label="厂家名称"
                       min-width="100">
      </el-table-column>
      <el-table-column align="center"
                       prop="enName"
                       label="厂家英文名称"
                       min-width="120">
      </el-table-column>
      <el-table-column align="center"
                       prop="creditCode"
                       label="信用代码"
                       min-width="120">
      </el-table-column>
      <el-table-column align="center"
                       prop="address"
                       label="厂家地址"
                       min-width="120">
      </el-table-column>
      <el-table-column align="center"
                       prop="createTime"
                       label="录入时间"
                       min-width="120"
                       :formatter="formatterDate">
      </el-table-column>
      <el-table-column align="center"
                       prop="productLicenseName"
                       label="生产许可证名称"
                       min-width="120">
      </el-table-column>
      <el-table-column align="center"
                       prop="medicalDeviceCertificateName"
                       label="注册证名称"
                       min-width="120">
      </el-table-column>
      <el-table-column label="操作"
                       min-width="120"
                       align="center">
        <template slot-scope="scope">
          <el-button type="primary"
                     @click="edit(scope.row.id)">编 辑
          </el-button>
          <el-button type="danger"
                     @click="deleteData(scope.row)">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <page @getList="initTable"
          :pageTotal="totals"
          ref="page">
    </page>
    <!-- 添加弹窗 -->
    <el-dialog title="厂家详情"
               width="40%"
               :close-on-click-modal="false"
               :visible.sync="dialogFormVisible">
      <el-form :model="factoryDetail"
               :rules="rules"
               ref="ruleFormRef">
        <el-form-item :label-width="formLabelWidth"
                      label="图标">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="factoryDetail.imageUrl"
                 :src="factoryDetail.imageUrl"
                 width="200px"
                 height="100px"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="厂家名称"
                      prop="name">
          <el-input v-model="factoryDetail.name"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="英文名称">
          <el-input v-model="factoryDetail.enName"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="营业执照">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess1"
                     :before-upload="beforeAvatarUpload">
            <img v-if="factoryDetail.businessLicenseUrl"
                 :src="factoryDetail.businessLicenseUrl"
                 width="200px"
                 height="100px"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="信用代码">
          <el-input v-model="factoryDetail.creditCode"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="厂家地址">
          <el-input v-model="factoryDetail.address"></el-input>
        </el-form-item>

        <el-form-item :label-width="formLabelWidth"
                      label="介绍">
          <el-input v-model="factoryDetail.introduce"
                    type="textarea"></el-input>
        </el-form-item>

        <el-form-item :label-width="formLabelWidth"
                      label="备注">
          <el-input v-model="factoryDetail.remark"
                    type="textarea"></el-input>
        </el-form-item>
        <el-button type="primary"
                   icon="el-icon-plus"
                   size="mini"
                   style="margin-bottom:20px;margin-left:70px"
                   @click="handleAdd">添加</el-button>
        <el-table border
                  style="width:90%; margin-left:70px"
                  :data="addTableData">
          <el-table-column label="生产许可证">
            <template slot-scope="scope">
              <el-input :disabled="scope.row.isProductLicenseIdFlag == undefined || scope.row.isProductLicenseIdFlag ? false: true"
                        v-model="scope.row.productLicenseName ">
              </el-input>

            </template>
          </el-table-column>
          <el-table-column label="注册证">
            <template slot-scope="scope">
              <el-input :disabled="scope.row.isIdFlag == undefined || scope.row.isIdFlag ? false: true"
                        v-model="scope.row.name ">
              </el-input>

            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- <el-button size="mini"
                         type="primary"
                         @click="handleEdit(scope.row, scope.$index)">编辑</el-button> -->
              <el-button size="mini"
                         type="danger"
                         @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-dialog width="30%"
                 title="编辑"
                 :visible.sync="innerVisible"
                 append-to-body>
        <el-form label-width="120px">
          <el-form-item label="生成许可证">
            <el-input v-model="editInfo.productLicenseName"
                      :disabled="!editInfo.isProductLicenseIdFlag"
                      class="w-220"></el-input>
          </el-form-item>
          <el-form-item label="注册证">
            <el-input v-model="editInfo.name"
                      :disabled="!editInfo.isIdFlag"
                      class="w-220"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="handleEditSave()">保 存</el-button>
        </div>
      </el-dialog>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveData()">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Vue from 'vue'
  import Page from '@/base/page/page'
  import { mapGetters } from 'vuex'

  export default {
    name: "factoryList",
    data () {
      return {
        searchCondition: '',
        formLabelWidth: '120px',
        imageUploadUrl: this.api.hospitalManager.uploadImg,
        dataList: [],
        totals: 0,
        dialogFormVisible: false,
        factoryDetail: {
          imageUrl: '', // 图标
          name: '', // 厂家名称
          enName: '', // 英文名称
          businessLicenseUrl: '', // 营业执照
          creditCode: '', // 信用代码
          address: '', // 厂家地址
          introduce: '', // 介绍
          remark: '', // 备注
          medicalDeviceCertificateDtos: []
        },
        rules: {
          name: [
            { required: true, message: '请输入厂商名称', trigger: 'blur' },
            { max: 50, message: '长度在50个字符', trigger: 'blur' }
          ]
        },
        addTableData: [],
        innerVisible: false,
        editInfo: {},
      }
    },
    created () {
      this.initTable();
    },
    methods: {
      query () {
        this.page.pageIndex = 0;
        this.initTable();
      },
      initTable () {
        let param = {
          name: this.searchCondition,
          pageSize: this.page.pageSize,
          pageIndex: this.page.pageIndex
        };
        this.post(this.api.factory.getFactoryInfoPage, param).then((res) => {
          if (res.data.code === '200') {
            this.dataList = res.data.object;
            this.totals = res.data.totalNum;
          } else {
            this.$message.error(res.data.message);
          }
        });
      },
      // 查询详情
      edit (id) {
        this.dialogFormVisible = true;
        if (id) {
          this.post(this.api.factory.getFactoryInfo, {
            id: id
          }).then((res) => {
            if (res.data.code === '200') {
              let resData = res.data.object
              this.factoryDetail = resData
              resData.medicalDeviceCertificateDtos = resData.medicalDeviceCertificateDtos == undefined ? [] : resData.medicalDeviceCertificateDtos;
              let strArr = []
              resData.medicalDeviceCertificateDtos.map(item => {

                let str = []
                let str1 = []
                let isProductLicenseIdFlag = true
                let isIdFlag = true
                str.push({
                  productLicenseId: item.productLicenseId,
                  id: ''
                })
                this.post(this.api.testStrip.allowEdit, {
                  medicalDeviceCertificateDtos: str
                }).then(res => {
                  if (res.data.code === '200') {
                    if (!res.data.object) {
                      isProductLicenseIdFlag = false
                    }
                  }
                  str1.push({
                    productLicenseId: "",
                    id: item.id
                  })
                  this.post(this.api.testStrip.allowEdit, {
                    medicalDeviceCertificateDtos: str1
                  }).then(resData => {
                    if (resData.data.code === '200') {
                      if (!resData.data.object) {
                        isIdFlag = false
                      }
                    }
                    item.isProductLicenseIdFlag = isProductLicenseIdFlag
                    item.isIdFlag = isIdFlag
                    strArr.push(item)
                  })
                })
              })

              this.addTableData = strArr;
              this.addTableData.sort((a, b) => {
                return a.id - b.id
              })
            } else {
              this.$message.error(res.data.message);
            }
          });
        }
      },

      // 删除数据
      async deleteData (row) {
        const { data: res } = await this.post(this.api.testStrip.allowEdit, {
          medicalDeviceCertificateDtos: row.medicalDeviceCertificateDtos
        })
        if (res.code === '200') {
          if (!res.object) {
            this.$message.warning('存在关联数据,不可删除')
          } else {
            const { data: resData } = await this.post(this.api.factory.deleteFactory, { id: row.id })
            if (resData.code === '200') {
              this.$message.success('删除成功')
              this.initTable();
            } else {
              this.$message.error(resData.message);
            }
          }
        }
      },
      // 动态添加行
      handleAdd () {
        this.addTableData.push({
          productLicenseName: '',
          name: ''
        })
      },
      // 动态删除行
      async handleDelete (index) {
        let { id, productLicenseId } = this.addTableData[index]
        if (id || productLicenseId) {
          let strArr = []
          strArr.push({
            id: id,
            productLicenseId: productLicenseId
          })
          const { data: res } = await this.post(this.api.testStrip.allowEdit, {
            medicalDeviceCertificateDtos: strArr
          })
          if (res.code === '200') {
            if (!res.object) {
              this.$message.error('存在关联数据,不可删除')
            } else {
              this.addTableData.splice(index, 1)
              this.$message.success('删除成功')
            }
          }
        } else {
          this.addTableData.splice(index, 1)
        }

      },
      // 动态编辑行
      async handleEdit (row, index) {
        this.editInfo = row
      },
      async handleEditSave () {
        this.innerVisible = false
      },
      handleSpan ({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 ||
          columnIndex === 5 || columnIndex === 8) {
          if (row.rowspan) {
            if (row.rowspan == -1) {
              return {
                rowspan: 0,
                colspan: 0
              };
            }
            if (row.rowspan > 1) {
              return {
                rowspan: row.rowspan,
                colspan: 1
              };
            }
          } else {
            return {
              rowspan: 1,
              colspan: 1
            };
          }
        }
      },
      // 提交数据
      saveData () {
        this.factoryDetail.medicalDeviceCertificateDtos = this.addTableData
        this.$refs['ruleFormRef'].validate((valid) => {
          if (valid) {
            this.post(this.api.factory.uploadFactoryInfo, this.factoryDetail).then((res) => {
              if (res.data.code === '200') {
                this.initTable();
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.data.message);
              }
            });
          }
        });

      },
      formatterDate (row) {
        return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm:ss')
      },
      handleAvatarSuccess (res) {
        this.factoryDetail.imageUrl = res.data;
      },
      handleAvatarSuccess1 (res) {
        this.factoryDetail.businessLicenseUrl = res.data;
      },

      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
    },
    computed: {
      ...mapGetters(['page'])
    }
    ,
    components: {
      Page,
    }
  }
</script>

<style scoped>
  .w-220 {
    width: 220px;
  }
</style>
